package org.mikhaylov.cp.web.command.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.mikhaylov.cp.service.command.ServiceCommandContainer;
import org.mikhaylov.cp.service.db.entities.User;
import org.mikhaylov.cp.service.response.Response;
import org.mikhaylov.cp.service.response.ResponseType;
import org.mikhaylov.cp.web.command.WebCommand;
import org.mikhaylov.cp.web.storage.Path;

public class RefillWebCommand extends WebCommand {

	private Logger log = Logger.getLogger(RefillWebCommand.class);
	
	private User user = null;
	private Double value = null;
	
	private static final long serialVersionUID = -541262956003482056L;

	@Override
	protected boolean checkParams(HttpServletRequest request) {
		if (request.getSession().getAttribute("user") == null
				|| request.getParameter("value") == null 
				|| request.getParameter("value").isEmpty()) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", "Bad parameters");
			return false;
		}
		return true;
	}

	@Override
	protected boolean extractParams(HttpServletRequest request) {
		user = (User) request.getSession().getAttribute("user");
		value = Double.valueOf(request.getParameter("value"));
		return true;
	}

	@Override
	protected void process(HttpServletRequest request) {
		request.setAttribute("user", user);
		request.setAttribute("value", value);
		Response r = ServiceCommandContainer.get("refill").execute(request, null);
		if (r.getType() == ResponseType.ERROR) {
			forward = Path.PAGE_ERROR;
			request.setAttribute("errorMessage", r.getMeta());
			log.debug(r.getMeta());
			return;
		}
		forward = Path.PAGE_PRG;
		request.setAttribute("next", Path.COMMAND_R_MENU);
		request.getSession().setAttribute("user", request.getAttribute("user"));
	}

}
